Browser Compatibility: NS2.02+, IE4+
|
So, you want to set things to happen after a certain amount of time? Well, the setTimeout function can help you create some nice scripts that will use time delays to make things happen. Let's take a look at how to call the setTimeout function:
setTimeout("yourfunction()",1000);
The first parameter is a string, which is going to be the function you want to use. This fuction was named "myfunction()". The second parameter is a number. This number is going to be the number of milliseconds the browser should wait before executing your function. Above, we have 1000 milliseconds, which will be 1 second.
Now, what can you do with it? Let me start with an example that shows you the setTimeout function in action. Click the button to the right of the text box below and watch what happens!
Now, how did I get that text to change a second time while you were able to just watch? Let's look at the script for this trick:
<HEAD> <SCRIPT language="JavaScript"> <!--hide function newtext() { document.myform.mytext.value="Hey! I have changed!"; setTimeout("moretext()",1000); } function moretext() { document.myform.mytext.value="I just change with the time!"; } //--> </SCRIPT> </HEAD> <BODY> <FORM name="myform"> <INPUT type="text" name="mytext" value="Not Much Here." size="30"> <INPUT TYPE="button" name="but1" value="Click!" onClick="newtext()"> </FORM>
We use the HEAD section to define our two functions. The first function is named "newtext()". We call this function when the user clicks the button we created. As you can see, we changed the value of the text in the text box by using the name of the form and the name of the textbox:
document.myform.mytext.value="Hey! I have changed!";
The next command is what makes the second change happen. We call the function "moretext()" after 1000 milliseconds:
setTimeout("moretext()",1000);
Now, the function "moretext()" changes the value in the form box one more time, after waiting 1 second:
document.myform.mytext.value="I just change with the time!";
Now, in the BODY section, we simply put the code for the form and the textbox. Remember to give your form and your textbox names. That is how we are able to change the text in the box using the functions. The name for the form above was "myform", and the name of the text box was "mytext".
If you need more help on how to access form elements, see a previous tutorial Beginning with Forms
Now you know how to call another function of your choice after a certain amount of time. This will allow you to create some pretty fun scripts. Well, the next section is on Beginning with Frames!
The tutorials and articles on these pages are © 1997-99 by John Pollock and may not be reposted without written permission from the author, and may not be reprinted for profit. |
|
![]() |
Email: [email protected] |
![]() |